﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DnPakExplorer {
	/// <summary>
	/// 物品背包管理
	/// </summary>
	public class BagPanel {

		/// <summary>
		/// 背包物品变化事件
		/// </summary>
		public event EventHandler OnBagItemChanged;

		/// <summary>
		/// 物品列表，元素可以为空，空元素表示一个空格子，没有物品
		/// </summary>
		private List<IUserItem> mItems;
		private Character mCharacter;

		public BagPanel(Character ch) {
			mItems = new List<IUserItem>();
			mCharacter = ch;
			mCharacter.OnCharacterClosed += mCharacter_OnCharacterClosed;
		}

		/// <summary>
		/// 处理角色关闭事件
		/// </summary>
		void mCharacter_OnCharacterClosed(object sender, EventArgs e) {
			foreach (IUserItem item in mItems) {
				if (item == null)
					continue;
				if (item.AppliedSlotsList != null) {
					foreach (IItemSlot slot in item.AppliedSlotsList) {
						slot.CleanupEvents();
					}
				}
				if (item.AppliedImprintingSlot != null) {
					item.AppliedImprintingSlot.CleanupEvents();
				}
			}
		}

		public Character Character {
			get { return mCharacter; }
		}

		/// <summary>
		/// 向背包添加物品，重复添加会引发异常
		/// </summary>
		/// <param name="item"></param>
		/// <returns>成功返回true</returns>
		public bool AddItem(IUserItem item) {
			if (mItems.Contains(item)) {
				throw new Exception("不允许多次添加同一个物品");
			}
			bool add = false;
			for (int i=0; i<mItems.Count; i++) {
				if (mItems[i] == null) {
					mItems[i] = item;
					add = true;
					break;
				}
			}
			if (!add)
				mItems.Add(item);
			if (OnBagItemChanged != null) {
				OnBagItemChanged(this, new EventArgs());
			}
			return true;
		}

		/// <summary>
		/// 从移除指定物品item
		/// </summary>
		/// <returns>成功移除放回true</returns>
		public bool RemoveItem(IUserItem item) {
			int index = mItems.IndexOf(item);
			if (index >= 0) {
				mItems[index] = null;
				if (OnBagItemChanged != null) {
					OnBagItemChanged(this, new EventArgs());
				}
				return true;
			} else
				return false;
		}

		/// <summary>
		/// 从指定位置index处移除物品
		/// </summary>
		/// <param name="index"></param>
		/// <returns>返回移除的物品，如果要移除的位置为空，则返回空</returns>
		public IUserItem RemoveItemAt(int index) {
			IUserItem oldItem = mItems[index];
			mItems[index] = null;
			if (OnBagItemChanged != null && oldItem!=null) {
				OnBagItemChanged(this, new EventArgs());
			}
			return oldItem;
		}

		/// <summary>
		/// 背包容量
		/// </summary>
		public int BagSize {
			get { return mItems.Count; }
		}

		/// <summary>
		/// 索引index处的物品
		/// </summary>
		public IUserItem this[int index] {
			get { return mItems[index]; }
		}

	}
}
